package com.gzsxy.esjy.gateway.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.support.NameUtils;
import org.springframework.stereotype.Component;
import springfox.documentation.swagger.web.SwaggerResource;
import springfox.documentation.swagger.web.SwaggerResourcesProvider;

import java.util.ArrayList;
import java.util.List;

/**
 * @author xiaolong
 * @version 1.0
 * @description: 网关swagger接口测试
 * @date 2021/11/15 16:12
 */
@Component
public class SwaggerProvider implements SwaggerResourcesProvider {

    public static final String API_URI = "/v2/api-docs";

    @Autowired
    private CustomRouteRepository routeRepository;

    @Value("${server.port}")
    private int port;

    @Value("${spring.cloud.client.ip-address}")
    private String ip;

    @Override
    public List<SwaggerResource> get() {
        ArrayList<SwaggerResource> resources = new ArrayList<>();
        resources.add(swaggerResource("网关","http://"+ip+":"+port+"/v2/api-docs"));
        //获取路由信息
        routeRepository.getRoutes()
                .forEach(routeDefinition -> routeDefinition.getPredicates().stream()
                        //获取所有的path断言，路径相匹配的进行路由  equalsIgnoreCase 忽略大小写
                .filter(predicateDefinition -> ("path").equalsIgnoreCase(predicateDefinition.getName()))

                .forEach(predicateDefinition -> resources
                        //该_genkey_前缀是固定的，自定义必须要使用这种规定，其实就是path = “login/**”
                .add(swaggerResource(routeDefinition.getId(),predicateDefinition.getArgs()
                        //将某/SERVICE-CORE/admin/core/**  替换为/SERVICE-CORE/admin/core/v2/api-docs
                .get(NameUtils.GENERATED_NAME_PREFIX+"0").replace("/**",API_URI)))));


        return resources;
    }



    private SwaggerResource swaggerResource(String name,String location){
        SwaggerResource swaggerResource = new SwaggerResource();
        swaggerResource.setName(name);
        swaggerResource.setLocation(location);
        swaggerResource.setSwaggerVersion("2.0");
        return swaggerResource;
    }
}
